package com.stars.easyms.schedule.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Set;

/**
 * 系统信息工具类
 *
 * @author guoguifang
 */
public final class SystemUtils {

    private static final Logger logger = LoggerFactory.getLogger(SystemUtils.class);

    private static String hostIp;

    private static String port;

    public static synchronized boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().contains("windows")) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /**
     * 获取本机ip地址，并自动区分Windows还是linux操作系统
     *
     * @return String
     */
    public static synchronized String getHostIp() {
        if (hostIp != null && hostIp.length() != 0) {
            return hostIp;
        }

        InetAddress inetAddress = null;
        try {
            //如果是Windows操作系统
            if (isWindowsOS()) {
                inetAddress = InetAddress.getLocalHost();
            }
            //如果是Linux操作系统
            else {
                boolean bFindIP = false;
                Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    NetworkInterface networkInterface = netInterfaces.nextElement();
                    String networkInterfaceName = networkInterface.getName().toLowerCase();
                    if (!networkInterfaceName.contains("docker") && !networkInterfaceName.contains("lo")) {
                        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                        while (inetAddresses.hasMoreElements()) {
                            inetAddress = inetAddresses.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                String ipAddress = inetAddress.getHostAddress();
                                if (!ipAddress.contains(":") && !ipAddress.contains("fe80")) {
                                    bFindIP = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (bFindIP) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("读取系统ip地址失败", e);
        }

        if (null != inetAddress) {
            hostIp = inetAddress.getHostAddress();
        }
        return hostIp;
    }

    public static synchronized String getPort() {
        if (port != null && port.length() != 0) {
            return port;
        }
        try {
            MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
            Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            port = objectNames.iterator().next().getKeyProperty("port");
        } catch (Exception e) {
            port = PropertyPlaceholderUtil.replace("server.port", "8080");
            logger.warn("读取系统端口号失败，使用默认端口号：{}", port);
        }
        return port;
    }

    private SystemUtils() {
        super();
    }
}
